<?php

/*
 * This file is part of the gedongdong/laravel_rbac_permission.
 *
 * (c) gedongdong <gedongdong2010@163.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Models\User;
use App\Library\Response;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Exceptions\UserException;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * @name 接口登录
     * @notes []
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        try {
            // 传参
            $email = $request->input('email', '');
            $password = $request->input('password', '');

            // 验证
            $user = User::query()->where('email', $email)->first();
            if (!$user || !Hash::check($password, $user->password)) {
                throw new UserException('登录失败!', Response::LOGIN_ERROR);
            }
            $data = [
                'remember_token' => hash('sha256', $password)
            ];
            // 更新token
            User::query()->where('id', $user->id)->update($data);

            return Response::response(['code' => Response::OK, 'msg' => '登录成功', 'data' => $data]);
        } catch (UserException $userException) {
            return Response::response(['code' => $userException->getCode(), 'msg' => $userException->getMessage()]);
        }
    }

    /**
     * @name 登出
     * @notes []
     *
     * @param Request $request
     */
    public function loginOut(Request $request)
    {
        // 登出接口
    }

    /**
     * @name 注册接口
     * @notes []
     *
     * @param Request $request
     */
    public function register(Request $request)
    {
        // 注册接口
    }
}
